package com.seray.zebraprintlib.base;

import com.seray.zebraprintlib.config.FontType;
import com.seray.zebraprintlib.content.AZebraContent;

import java.util.Map;

/**
 * Author：李程
 * CreateTime：2018/8/10 16:30
 * E-mail：licheng@kedacom.com
 * Describe：
 */
public class BaseLabel<D> {

    /**
     * 回车
     */
    private static final String BREAK = "\r\n";

    /**
     * 标签宽度
     */
    private int width;

    /**
     * 标签高度
     */
    private int height;

    /**
     * 打印标签数量
     */
    private int count;

    @FontType
    private String fontType;

    /**
     * 属性内容集合
     */
    private Map<String, AZebraContent> params;

    private BaseLabelBuilder<D> mBuilder;

    BaseLabel(BaseLabelBuilder<D> builder) {
        this.mBuilder = builder;
        this.fontType = builder.getFontType();
        this.width = mBuilder.getWidth();
        this.height = mBuilder.getHeight();
        this.count = mBuilder.getCount();
        this.params = mBuilder.getParams();
    }

    public String format() {
        if (this.mBuilder.getData() == null)
            throw new NullPointerException("print data is null,method data() must be called before build");
        String content = content();
        if (content == null || content.isEmpty())
            throw new NullPointerException("print content was empty,method param() must be called before build");
        return header() + content + footer();
    }

    private String content() {
        if (params.isEmpty())
            return null;
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, AZebraContent> entry : params.entrySet()) {
            AZebraContent content = entry.getValue();
            if (content == null)
                continue;
            String lineStr = content.install();
            sb.append(lineStr);
        }
        return sb.toString();
    }

    private String header() {
        return "^XA~TA000~JSN^LT0^MNW^MTD^PON^PMN^LH0,0^JMA^PR4,4~SD15^JUS^LRN^CI0^XZ" + BREAK
                + "^XA^CW1," + fontType + BREAK
                + "^CI28" + BREAK
                + "^MMT" + BREAK
                + String.format("%s%s", "^PW", width) + BREAK
                + String.format("%s%s", "^LL", height) + BREAK
                + "^LS0" + BREAK;
    }

    private String footer() {
        return String.format("%s%s", "^PQ", count) + BREAK + "^XZ";
    }

    public BaseLabelBuilder<D> getBuilder() {
        return mBuilder;
    }
}
